<template>
  <div class="app-container">
    <div
      v-show="
        !modifyInfo.visible && !detailInfo.visible && !detailListInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <new-page-filter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slipSelectRequest="slipSelectRequest"
        >
        </new-page-filter>
        <el-button @click="detailListInfo.visible = true">明细页</el-button>
      </div>
      <div class="filter-wrapper">
        <new-page-filter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-remove>
            <el-button
              :disabled="!canRemove"
              @click="remove(tableInfo.selections)"
              >删除
            </el-button>
          </template>
        </new-page-filter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <TableContainer
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          <span
            v-if="$permission('provincePayOrder:detail')"
            class="slip-edit"
            @click="showDetail(scope.row)"
            >{{ scope.row.orderNo || '-' }}</span
          >
          <span v-else>{{ scope.row.orderNo || '-' }}</span>
        </template>
      </TableContainer>
    </div>
    <!-- 新增或修改 -->
    <modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :orderId="modifyInfo.orderId"
      @returnModify="returnModify"
    />
    <detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :orderId="detailInfo.orderId"
      @returnBack="getList"
    />

    <SetPreference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
    <AdvancedSearch
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <detailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></detailList>
  </div>
</template>
<script setup name="provincePayOrder">
import {
  provincePayOrderCustomizeListPage,
  provincePayOrderRemove,
  provincePayOrderSubmit,
} from '@/api/province'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import modify from './modify'
import detail from './detail'

const detailList = defineAsyncComponent(() => import('./detailList'))

const { proxy } = getCurrentInstance()

const listTypeInfo = ref({
  supplierList: [],
  typeList: [],
})
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {},
  },
  searchList: [],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('provincePayOrder:add'),
    },
    {
      type: 'slot',
      value: 'remove',
      show: proxy.$permission('provincePayOrder:delete'),
    },
  ],
  searchBtn: [
    { type: 'button', label: '搜索', event: _search },
    { type: 'button', label: '高级查询', event: _advancedSearchShow },
    { type: 'button', label: '重置', event: _clearSearch },
  ],
})
const detailListInfo = ref({
  visible: false,
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const clearType = ref(true)
const slipSelectRequest = ref(true)
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '修改',
        event: update,
        show: proxy.$permission('provincePayOrder:update'),
        ifRender: function (row) {
          return row.status === 0
        },
      },
      {
        label: '提交',
        event: submit,
        show: proxy.$permission('provincePayOrder:submit'),
        ifRender: function (row) {
          return row.status === 0
        },
      },

      {
        label: '删除',
        event: remove,
        show: proxy.$permission('provincePayOrder:delete'),
        popconfirmText: '删除后将改变数据,是否继续？',
        ifRender: function (row) {
          return row.status === 0
        },
      },
    ],
  },
})
//明细相关
const detailInfo = ref({
  visible: false,
  orderId: '',
})

//新增或更新相关
const modifyInfo = ref({
  visible: false,
  title: '',
  orderId: '',
})

const tableKey = ref(
  'provincePayOrderList-com.slip.spd.entity.vo.provincePlatform.ProvincePayOrderVO'
)
const canRemove = computed(() => {
  return (
    tableInfo.value.selections.filter((item) => item.status === 0).length !== 0
  )
})
const canSubmit = computed(() => {
  return (
    tableInfo.value.selections.filter((item) => item.status === 0).length !== 0
  )
})

const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})

let stopWatch = function () {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === 'purchOrder' && el.url === val.url) {
                detailInfo.value.visible = false
                modifyInfo.value.visible = false
                detailInfo.value.visible = false
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  proxy.$nextTick(() => {
                    detailInfo.value.visible = true
                    detailInfo.value.orderId = val.businessId
                    sessionStorage.setItem('storeRowId', val.businessId)
                  })
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    {
      deep: true,
      immediate: true,
    }
  )
})
onDeactivated(() => {
  stopWatch()
})

setData()
function setData() {
  let obj = {
    statusValue: {
      label: '状态',
      value: 'statusValue',
      asValue: 'status',
      componentType: 'select-model',
      code: 'province_pay_status',
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
}
function _search() {
  search()
}
function _advancedSearchShow() {
  advancedSearchShow()
}
function _clearSearch() {
  clearSearch()
}

function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
// 获取列表
async function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }

  return ''
}

function returnModify() {
  if (modifyInfo.value.orderId) {
    getList()
  } else {
    search()
  }
}

// 创建
function create() {
  modifyInfo.value.visible = true
  modifyInfo.value.title = '新增省采订单支付'
  modifyInfo.value.orderId = ''
}
// 编辑
function update(data) {
  sessionStorage.setItem('storeRowId', data.id)
  modifyInfo.value.visible = true
  modifyInfo.value.title = '修改省采订单支付'
  // 显示信息
  modifyInfo.value.orderId = data.id
}
//删除
function remove(row = undefined) {
  let ids = []
  if (Array.isArray(row)) {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        ids = row.map((i) => i.id)
        provincePayOrderRemove(ids).then((res) => {
          if (res && res.success) {
            getList()
          }
        })
      })
  } else {
    ids.push(row.id)
    provincePayOrderRemove(ids).then((res) => {
      if (res && res.success) {
        getList()
      }
    })
  }
}
//展示明细
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.value.orderId = row.id
  detailInfo.value.visible = true
}

async function advancedSearchCallback(obj) {
  let _filterInfo = filterInfo.value
  _filterInfo.query.queryMap = {}
  let arr = []
  _filterInfo.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.value.data = obj.data
  await getList()
  clearType.value = !clearType.value
  _filterInfo.query.queryMap = proxy.$fn.deepClone(_filterInfo.copyQueryMap)
}
function submit(row = undefined) {
  provincePayOrderSubmit([row.id]).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}

function getCustomize(_slipSelectRequest = true) {
  let _tableInfo = tableInfo.value
  let _filterInfo = filterInfo.value
  let param = {
    tableKey: tableKey.value,
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      _tableInfo.fieldList = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail
      )
      console.log(_tableInfo.fieldList)
      let searchInfo = proxy.$fn.setSearchList(
        _filterInfo.searchList,
        data.detail
      )
      _filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ..._filterInfo.query.queryMap,
      }
      _filterInfo.searchList = searchInfo.searchList
      _filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      _tableInfo.api = provincePayOrderCustomizeListPage
      getList()
    }
  })
}
</script>

<style scoped lang="scss"></style>
